package cn.com.wblog.modules;

import javax.servlet.http.HttpSession;

import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import cn.com.wblog.dao.UserDao;
import cn.com.wblog.pojo.User;
import cn.com.wblog.utils.Utils;

@IocBean
@InjectName
public class LoginoutModule {

	@Inject
	private UserDao userDao;
	@At
	@Ok("redirect:/admin/index")
	@Fail("redirect:/login.jsp")
	public void login(@Param("username") String username, 
			@Param("password") String password,
			@Param("code") String code,
			HttpSession session) {
		String sCode = (String)session.getAttribute("code");
		if (code == null || !sCode.equals(code)) {
			throw new RuntimeException("Error code");
		}
		User user = userDao.getUser(username, Utils.MD5Code(password));
		if (user == null) {
			throw new RuntimeException("Error code");
		} else {
			session.setAttribute("user", user);
			session.setAttribute("role", user.getRole());
		}
		return;
	}
	
	@At
	@Ok("redirect:/login.jsp")
	public void logout(HttpSession session) {
		session.setAttribute("user", null);
		session.setAttribute("role", null);
	}
}
